package com.health.mapp.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;


public class FtpClient 
{
	private Logger logger = Logger.getLogger(FtpClient.class);
	
	private FTPClient ftpClient;
	
	private String ip;
	
	private int port;
	
	private String username;
	
	private String password;
	
	private String localPath;
	
	private String remotePath;
	
	private String localFileName;
	
	private String remoteFileName;
	
	private String configPath;
	
	private File uploadFile;
	
	public FtpClient()
	{
		ftpClient = new FTPClient();
	}
	
	/**
	 * 
	 * ���캯��
	 * @param ip
	 * @param port
	 * @param username
	 * @param password
	 */
	public FtpClient(String ip, int port, String username, String password)
	{
		ftpClient = new FTPClient();
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.password = password;
	}
	
	public FtpClient(String ip, int port, String username, String password, 
			String localPath, String localFileName,
			String remotePath, String remoteFileName)
	{
		ftpClient = new FTPClient();
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.password = password;
		this.localPath = localPath;
		this.localFileName = localFileName;
		this.remotePath = remotePath;
		this.remoteFileName = remoteFileName;
	}
	
	public FtpClient(String ip, int port, String username, String password, 
			String localPath, String localFileName,
			String remotePath, String remoteFileName,
			String configPath)
	{
		ftpClient = new FTPClient();
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.password = password;
		this.localPath = localPath;
		this.localFileName = localFileName;
		this.remotePath = remotePath;
		this.remoteFileName = remoteFileName;
		this.configPath = configPath;
	}
	
	
	/**
	 * ����
	 * connect
	 *
	 * @return
	 * @throws Exception boolean
	 * @Exception
	 * @author��yuchong
	 * @2013-6-3 ����02:49:57 
	 * @update:
	 * @2013-6-3 ����02:49:57
	 */
	public boolean connect()throws Exception
	{
		return this.getConnect(this.ip, this.port, this.username, this.password);
	}
	
	/**
	 * ��ȡ����
	 * getConnect
	 *
	 * @param ip
	 * @param port
	 * @param username
	 * @param password
	 * @return boolean
	 * @Exception
	 * @author��yuchong
	 * @2013-6-3 ����02:49:40 
	 * @update:
	 * @2013-6-3 ����02:49:40
	 */
	public boolean getConnect(String ip, int port, String username, String password)
	{
		try
		{
	//		ftpClient.setConnectTimeout(10000);
			ftpClient.connect(ip, port);
			ftpClient.login(username, password);
			ftpClient.setControlEncoding("UTF-8");
			ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
			//if ReplyCode=230 login success
			//
			if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
				logger.error("get  ftp Connect getReplyCode:"+ftpClient.getReplyCode()+" "+ftpClient.getReplyString());
				
				ftpClient.disconnect();
				logger.error("get  ftp Connect fail");
				
				return false;
			}else{
				logger.info("get  ftp Connect getReplyCode:"+ftpClient.getReplyCode()+" "+ftpClient.getReplyString());
				return true;
			}
			
		}catch(Exception e){
			logger.error("����FTP�쳣��  " + e.getMessage());
		}
		
		return false;
	}
	
	/**
	 * �˳���¼
	 * logout
	 *
	 * @throws Exception void
	 * @Exception
	 * @author��yuchong
	 * @2013-6-3 ����02:49:32 
	 * @update:
	 * @2013-6-3 ����02:49:32
	 */
	public void logout()throws Exception
	{
		if(null != ftpClient)
		{
			try{
				ftpClient.logout();	//�˳���¼
			}catch(Exception e){
				logger.error("ftp logout �쳣��" + e.getMessage());
			}
		}
	}
	
	/**
	 * �Ͽ�����
	 * disconnect
	 *
	 * @throws Exception void
	 * @Exception
	 * @author��yuchong
	 * @2013-6-3 ����02:49:23 
	 * @update:
	 * @2013-6-3 ����02:49:23
	 */
	public void disconnect()throws Exception
	{
		if(null != ftpClient)
		{
			try{
				ftpClient.logout();	 
				if(ftpClient.isConnected())
						ftpClient.disconnect();
			}catch(Exception e){
				logger.error("ftp disconnect Exception" );
				e.printStackTrace();
			}
		}
	}
	
	
	
	public FTPClient getFtpClient()
	{
		return ftpClient;
	}

	public void setFtpClient(FTPClient ftpClient)
	{
		this.ftpClient = ftpClient;
	}
	
	/**
	 * �ϴ�����
	 * uploadStatizeFile
	 *
	 * @param path
	 * @param vir_path
	 * @param file
	 * @throws Exception void
	 * @Exception
	 * @author��yuchong
	 * @2014-6-3 ����05:26:30 
	 * @update:
	 * @2014-6-3 ����05:26:30
	 */
	public void uploadStatizeFile(String chan_path, String vir_path, File file)throws Exception{
		FileInputStream is = null;
		try{
				logger.debug("------------begin----------");
				
				ftpClient.changeWorkingDirectory(chan_path);		//������������Ŀ¼��
				this.createDir(vir_path);					//�������������в㼶Ŀ¼
	//			ftpClient.changeWorkingDirectory(vir_path); //����Ŀ��Ŀ¼��
				
				is = new FileInputStream(file);				//�ļ���
				String fileName = file.getName();
				ftpClient.storeFile(fileName, is);//�ϴ�
				
				logger.debug("------------end----------");
				  
		}catch(Exception e){
			logger.error(e.getMessage());
			throw new Exception("�ϴ�ʧ�ܣ�" + e.getMessage());
		}finally{
			if(null != is)
				is.close();
			
		}
	}
	
	public void uploadStatizeFile(FtpClient client, String path, String vir_path, File file)throws Exception{
		FileInputStream is = null;
		try{
			if(client.connect()){
				logger.debug("------------begin----------");
				
	//			FTPClient ftpClient = client.getFtpClient();
				ftpClient.changeWorkingDirectory(path);
				this.createDir(vir_path);
	//			ftpClient.changeWorkingDirectory(vir_path);
				
				is = new FileInputStream(file);
				ftpClient.storeFile(file.getName() + ".html", is);
				
				logger.debug("------------end----------");
			}
		}catch(Exception e){
			logger.error(e.getMessage());
		}finally{
			if(null != is)
				is.close();
			
		}
	}
	
	/**
	 * �ϴ�ģ���ļ�
	 * uploadTemplFile
	 *
	 * @param basicPath
	 * @param chanPath
	 * @param file
	 * @throws Exception void
	 * @Exception
	 * @author��yuchong
	 * @2014-6-13 ����04:32:05 
	 * @update:
	 * @2014-6-13 ����04:32:05
	 */
	public void uploadTemplFile(String basicPath, String chanPath, File file)throws Exception{
		this.createDir(basicPath);
		this.createDir(chanPath);
		
		FileInputStream is = null;
		try{
			is = new FileInputStream(file);
			ftpClient.storeFile(file.getName(), is);
		}catch(Exception e){
			logger.error("" + e.getMessage());
			throw new Exception("ģ���ļ��ϴ�ʧ�ܣ�" + e.getMessage());
		}finally{
			if(null != is)
				is.close();
		}
	}
	
	public void uploadFile(String basicPath, String chanPath, File file)throws Exception{
		this.createDir(basicPath);
		this.createDir(chanPath);
		
		FileInputStream is = null;
		try{
			is = new FileInputStream(file);
			ftpClient.storeFile(file.getName(), is);
			logger.info("!!!!!ftp  uploadFile successfully!!!!!!");
		}catch(Exception e){
			logger.error("" + e.getMessage());
			throw new Exception("" + e.getMessage());
		}finally{
			if(null != is)
				is.close();
		}
	}
	
	public void deleteFile(String basicPath, String chanPath, String fileName)throws Exception{
		
		this.cd(basicPath);
		this.cd(chanPath);
		
		try{
			if(ftpClient.deleteFile(fileName)){
				logger.error("�ļ�ɾ��ɹ���");
			}else{
				logger.error("�ļ�ɾ��ʧ�ܣ�");
				throw new Exception("�ļ�ɾ��ʧ�ܣ�");
			}
		}catch(Exception e){
			logger.error("" + e.getMessage());
			throw new Exception("�ļ�ɾ��ʧ�ܣ�" + e.getMessage());
		}
	}
	
	/**
	 * �����ļ�
	 * downLoadFile
	 *
	 * @param remotePath
	 * @param remoteFileName
	 * @param localFileName
	 * @return
	 * @throws Exception File
	 * @Exception
	 * @author��yuchong
	 * @2014-6-13 ����05:04:56 
	 * @update:
	 * @2014-6-13 ����05:04:56
	 */
	public File downLoadFile(String remotePath, String remoteFileName, String localFileName)throws Exception{
		this.cd(remotePath);
		File localFile = new File(localFileName);	//sysPath + GoodsUtil.fileSep + 
		FileOutputStream fos = null;
		try{
			FTPFile[] remoteFiles = ftpClient.listFiles();
			for(FTPFile file: remoteFiles){
				if(remoteFileName.equals(file.getName())){
					fos = new FileOutputStream(localFile);
					ftpClient.retrieveFile(remoteFileName, fos);
				}
			}
		}catch(Exception e){
			logger.error("" + e.getMessage());
			throw new Exception("�����ļ�ʧ�ܣ�" + e.getMessage());
		}finally{
			if(null != fos)
				fos.close();
		}
		return localFile;
	}
	
	public String readFile(String path, String fileName)throws Exception{
		StringBuffer sb = new StringBuffer("");
		
		File file = null;
		BufferedReader br = null;
		try{
			file = this.downLoadFile(path, fileName, fileName);
			br = new BufferedReader(new FileReader(file));
			String lineS = null;
			while((lineS = br.readLine()) != null){
				sb.append(lineS + " \n");
			}
		}catch(Exception e){
			logger.error("��ȡ�ļ�ʧ�ܣ�" + e.getMessage());
			throw new Exception("��ȡ�ļ�ʧ�ܣ�" + e.getMessage());
		}finally{
			if(null != br)
				br.close();
			
			if(null != file && file.exists())
				file.delete();
		}
		return sb.toString();
	}
	
	/**
	 * ����FTPĿ¼
	 * createDir
	 *
	 * @param path
	 * @throws Exception void
	 * @Exception
	 * @author��yuchong
	 * @2014-6-3 ����05:11:40 
	 * @update:
	 * @2014-6-3 ����05:11:40
	 */
	public void createDir(String path)throws Exception
	{
		try
		{
			if(null != path && !"".equals(path)){
				String[] ftpFNs = this.getFtpFileNames(ftpClient); 	//��ȡFTPĿ¼���ļ��б���		ftpClient.listNames();
				if(path.contains("\\")|| path.contains("/")){		//	GoodsUtil.fileSepAudit	File.separator) || path.contains("\\")|| path.contains("/")
					int index = path.indexOf("/");		//"/" GoodsUtil.fileSepAudit
					String firstName = path.substring(0, index);	//��ǰĿ¼
					String lastName = path.substring(index+1, path.length());	//����Ŀ¼
					
					if(null != firstName && !"".equals(firstName)){
						
						if(!ArrayUtils.contains(ftpFNs, firstName)){		//�ж��б�Ŀ���Ƿ��Ѵ���
							ftpClient.makeDirectory(firstName);				//����Ŀ¼
						}
						ftpClient.changeWorkingDirectory(firstName);		//����Ŀ��Ŀ¼��
					}
					createDir(lastName);									//�ݹ���ô���Ŀ¼�㼶
					
				}else{
					if(!ArrayUtils.contains(ftpFNs, path)){
						if(ftpClient.makeDirectory(path)){
							logger.debug("true");
						}else{
							logger.debug("false");
						}
					}
					
					ftpClient.changeWorkingDirectory(path);
				}
			}
		}catch(Exception e){
			logger.error(e.getMessage());
			throw new Exception("�ϴ�ʧ�ܣ�" + e.getMessage());
		}finally{
			
		}
		
	}

	/**
	 * ��ȡFTP�ļ��������
	 * getFtpFileNames
	 *
	 * @param ftp
	 * @return
	 * @throws Exception String[]
	 * @Exception
	 * @author��yuchong
	 * @2014-6-3 ����05:12:13 
	 * @update:
	 * @2014-6-3 ����05:12:13
	 */
	public String[] getFtpFileNames(org.apache.commons.net.ftp.FTPClient ftp)throws Exception{
		
		FTPFile[] files = ftp.listFiles();
		String[] listNames = new String[files.length];
		for(int i=0; i<files.length; i++){
			listNames[i] = files[i].getName();
		}
		
		return listNames;
	}
	
	public void cd(String path)throws Exception{
		if(!this.isEmpty(path)){
			path = path.startsWith("/")?path.substring(1, path.length()):path;
			if(path.contains("/")){
				int index = path.indexOf("/");
				String firstName = path.substring(0, index);				//��ǰĿ¼
				String lastName = path.substring(index+1, path.length());	//����Ŀ¼
				ftpClient.changeWorkingDirectory(firstName);
				this.cd(lastName);
			}else{
				ftpClient.changeWorkingDirectory(path);
			}
		}
	}
	
	public static boolean isEmpty(Object obj){
		if(null != obj && !"".equals(obj)){
			return false;
		}else{
			return true;
		}
	}
	
	
	public static void  main(String[] args)throws Exception
	{
		
		FtpClient c= new FtpClient("192.168.11.72", Integer.valueOf("21"), "ecopapp", "123456");
		try{
			if(c.connect()){
				//e:\\uploadify
			File file = new File("C:\\test0909.txt");
			c.uploadFile("", "/ngboss/webapp", file);
			System.out.println("startt");
			}
			
		}catch (Exception e) {
			
			System.out.println("end");
		}finally{
			System.out.println("ok");
			c.disconnect();
		}
		
		
	}
}
